package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.TransportRPCService;
import id.net.iconpln.bb.client.service.TransportRPCServiceAsync;
import id.net.iconpln.bb.client.tools.ComboPembangkitPemasok;
import id.net.iconpln.bb.client.tools.ComboRakorPemasok;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.MultiField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbTransportloading extends LayoutContainer {
	private final TransportRPCServiceAsync service = GWT.create(TransportRPCService.class);
	private ListStore storePengajuan, storeResult, storeRakor, storePerjalanan;
	private Grid gridpltu, gridship;
	private TextField txtNoPengiriman, txtNoPreshipment, txtVolume, txtPelabuhan, txtPic, txtNoTelp;
	private DateField txtTgl, txtTglEtd, txtTglEta;
	private TimeField txtEtd, txtEta;
	private ComboBox cboRakor, cboPembangkit;
	private TextArea txtKeterangan;
	private FormPanel panel ;
	
	  @Override  
	  protected void onRender(Element parent, int index) {  
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());	    
	    initStore();
	    
	    ContentPanel cp = new ContentPanel();  	   
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));	  
	    
	    panel = createForm(); 
	    panel.setScrollMode(Scroll.AUTO);
	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);
	    p.setLayout(new RowLayout(Orientation.VERTICAL));	    
	    
	    ContentPanel cpShip = new ContentPanel();
	    cpShip.setLayout(new FitLayout());
	    gridship = createGridPreshipment();
	    gridship.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	txtNoPreshipment.setValue(gridship.getSelectionModel().getSelectedItem().get("no_pengajuan"));
            	txtVolume.setValue(gridship.getSelectionModel().getSelectedItem().get("volume"));
            	txtTgl.setRawValue(gridship.getSelectionModel().getSelectedItem().get("tanggal").toString());
            	txtTglEta.setRawValue(gridship.getSelectionModel().getSelectedItem().get("tanggal_eta").toString());
            	txtTglEtd.setRawValue(gridship.getSelectionModel().getSelectedItem().get("tanggal_etd").toString());    
            	txtEta.setRawValue(gridship.getSelectionModel().getSelectedItem().get("jam_eta").toString());
            	txtEtd.setRawValue(gridship.getSelectionModel().getSelectedItem().get("jam_eta").toString());
            	
            }
		});
	    cpShip.add(gridship);
	    
	    ToolBar tbJadwal = new ToolBar();
	    tbJadwal.add(new LabelToolItem("<b>Data Shipment</b>"));
	    tbJadwal.add(new SeparatorToolItem());
	    p.setTopComponent(tbJadwal);
	    
	    p.add(cpShip, new RowData(1, .5));
	    
	    ContentPanel cpLoading = new ContentPanel();
	    cpLoading.setHeading("Data Loading");
	    cpLoading.setLayout(new FitLayout());
	    gridpltu = createGridPltu();
	    gridpltu.addListener(Events.CellClick, new Listener<BaseEvent>() {            
            public void handleEvent(BaseEvent ge) {
            	txtNoPreshipment.setValue(gridpltu.getSelectionModel().getSelectedItem().get("no_pengajuan"));
            	txtVolume.setValue(gridpltu.getSelectionModel().getSelectedItem().get("volume"));
            	txtTgl.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("tanggal").toString());
            	txtTglEta.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("tanggal_eta").toString());
            	txtTglEtd.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("tanggal_etd").toString());    
            	txtEta.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("jam_eta").toString());
            	txtEtd.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("jam_eta").toString());
            	txtPelabuhan.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("pelabuhan").toString());
            	txtPic.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("pic").toString());
            	txtNoTelp.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("telp").toString());
            	txtKeterangan.setRawValue(gridpltu.getSelectionModel().getSelectedItem().get("keterangan").toString());
            }
		});
	    cpLoading.add(gridpltu);
	    p.add(cpLoading, new RowData(1, .5));	
	    
	    cp.add(panel, new RowData(.50, 1));
	    cp.add(p, new RowData(.50, .99));	    
	    add(cp, new FitData(5));  
	       
	  }  
	  
	  private void getListPengajuan(String no_rakor, String status, String id_pltu){
		  Map mapParam = new FastMap();
  		  mapParam.put("no_rakor", no_rakor);
  		  mapParam.put("id_pltu", id_pltu);
  		  mapParam.put("status", status);
  		  
  		  service.getListPengiriman("PENGAJUAN", mapParam,new AsyncCallback<List<Map>>() {
  			public void onFailure(Throwable caught) {
  				GWT.log(caught.getMessage(), null);
  			}

  			public void onSuccess(List<Map> result) {	
  				storePengajuan.removeAll();
  				storePengajuan.add(ClientModule.setListBaseModelFromListMap(result));
  			}
  		  });
  		  
  		  service.getListPengiriman("PERJALANAN", mapParam,new AsyncCallback<List<Map>>() {
  			public void onFailure(Throwable caught) {
  				GWT.log(caught.getMessage(), null);
  			}

  			public void onSuccess(List<Map> result) {	
  				GWT.log("PERJALANAN " + result.size());
  				storePerjalanan.removeAll();
  				storePerjalanan.add(ClientModule.setListBaseModelFromListMap(result));
  			}
  		  });
	  }
	  
	  private void initStore(){
		  storePengajuan = new ListStore(); 
		  storeRakor = new ListStore();
		  storePerjalanan = new ListStore();		  
		  storeResult = new ListStore(); 
		  
		  storeResult.addStoreListener(new StoreListener<ModelData>(){
			  @Override
				public void storeAdd(StoreEvent<ModelData> se) {
					super.storeAdd(se);
					MessageBox.alert("Information", se.getModels().get(0).get("message").toString(), null);  
				}			  
		  });
	  }
	  
	  private Grid createGridPreshipment(){		    		  
		  List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	 
		    column = new ColumnConfig("no_jadwal", "No Jadwal", 150);  
		    configs.add(column);  
		    
		    column = new ColumnConfig("no_pengajuan", "No PreShipment", 150);  
		    configs.add(column); 

		    column = new ColumnConfig("bulan_tahun", "BLTH", 100);  
		    configs.add(column);  	  
		    		  
		    column = new ColumnConfig("tanggal", "Tanggal", 100);  
		    configs.add(column);
		    
		    column = new ColumnConfig("id_transportir", "Transportir", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("id_kapal", "Kapal", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("volume", "Vol (Ton)", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("eta", "ETA", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("etd", "ETD", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("status", "Status", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("keterangan", "Keterangan", 150);  
		    configs.add(column);
		    storePengajuan.setMonitorChanges(true);  
		    ColumnModel cm = new ColumnModel(configs);
		    gridship = new Grid(storePengajuan, cm);  
		    gridship.getView().setEmptyText("Data Empty");  
		    gridship.setBorders(false);  	
		    return gridship;  
		  }   
	  
	  private FormPanel createForm() {  		
	    final FormPanel panel = new FormPanel();	    
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSetFilter = new FieldSet();  
	    fieldSetFilter.setHeading("Data Filter");  
	    fieldSetFilter.setCollapsible(false);
	    
	    FormLayout layoutFilter = new FormLayout();  
	    layoutFilter.setLabelWidth(100);  
	    fieldSetFilter.setLayout(layoutFilter);  
	    cboRakor = new ComboRakorPemasok(Registry.get("idPltu").toString());  
	    cboRakor.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		Map map = new FastMap();
	    	    map.put("no_rakor", cboRakor.getValue().get("no_rakor").toString());
	    	    map.put("id_pemasok", Registry.get("idPltu").toString());
	    	    service.getListPengendalian("PEMBANGKIT_BY_RAKOR", map, new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}

	    			public void onSuccess(List<Map> result) {	
	    				cboPembangkit.getStore().removeAll();
	    				cboPembangkit.getStore().add(ClientModule.setListBaseModelFromListMap(result));
	    			}
	    		});
	    	}
		});
	    fieldSetFilter.add(cboRakor);
	    
	    
	    cboPembangkit = new ComboPembangkitPemasok(Registry.get("idPltu").toString());
	    cboPembangkit.setWidth(200);
	    fieldSetFilter.add(cboPembangkit);
	    cboPembangkit.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		getListPengajuan(cboRakor.getValue().get("no_rakor").toString(), "ENTRY", 
	    	  			  cboPembangkit.getValue().get("id_pltu").toString());	    		
	    	}
		});
	    
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Pengajuan Loading");  
	    fieldSet.setCollapsible(false);
	  
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(100);  
	    fieldSet.setLayout(layout);  
	    
	    txtNoPengiriman = new TextField();
	    txtNoPengiriman.setName("no_pengiriman");  
	    txtNoPengiriman.setFieldLabel("No Pengiriman");	    
	    fieldSet.add(txtNoPengiriman);
	    
	    txtNoPreshipment = new TextField();
	    txtNoPreshipment.setName("no_pengajuan");  
	    txtNoPreshipment.setFieldLabel("No Pengajuan");	    
	    fieldSet.add(txtNoPreshipment);
	    
	    txtTgl = new DateField(); 
	    txtTgl.setName("tanggal");
	    txtTgl.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txtTgl.setFieldLabel("Tanggal");  
	    txtTgl.setData("text", "Enter Tanggal");      
	    fieldSet.add(txtTgl);	   
	    
	    txtTglEtd = new DateField(); 
	    txtTglEtd.setName("tanggal_etd");
	    txtTglEtd.setPropertyEditor(new DateTimePropertyEditor("d/MM/yyyy"));
	    txtTglEtd.setFieldLabel("Tanggal ETD");  
	    txtTglEtd.setData("text", "Enter Tanggal ETD");  
	    txtTglEtd.setWidth(100);
	    
	    txtEtd = new TimeField();
	    txtEtd.setName("time_etd");
	    txtEtd.setData("text", "Enter ETD"); 
	    txtEtd.setWidth(100);
	    txtEtd.setFormat(DateTimeFormat.getFormat("HH:mm"));
	    txtEtd.setIncrement(15);
	    
	    MultiField mfPanel1 = new MultiField();
	    mfPanel1.setSpacing(10);
	    mfPanel1.setFieldLabel("Tanggal TD");
	    mfPanel1.add(txtTglEtd);
	    mfPanel1.add(txtEtd);	    
	    fieldSet.add(mfPanel1);	   
	    
	    txtTglEta = new DateField(); 
	    txtTglEta.setName("tanggal_eta");
	    txtTglEta.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    txtTglEta.setFieldLabel("Tanggal ETA");  
	    txtTglEta.setData("text", "Enter Tanggal ETA");    
	    txtTglEta.setWidth(100);
	    
	    txtEta = new TimeField();
	    txtEta.setName("time_eta");
	    txtEta.setFieldLabel("ETA");  
	    txtEta.setFormat(DateTimeFormat.getFormat("HH:mm"));
	    txtEta.setIncrement(15);
	    txtEta.setWidth(100);
	    
	    MultiField mfPanel2 = new MultiField();
	    mfPanel2.setSpacing(10);
	    mfPanel2.setFieldLabel("Tanggal TA");
	    mfPanel2.add(txtTglEta);
	    mfPanel2.add(txtEta);
	    fieldSet.add(mfPanel2);	
	    
	    txtVolume = new TextField();
	    txtVolume.setName("volume");  
	    txtVolume.setFieldLabel("Volume");	    
	    fieldSet.add(txtVolume);
	    
	    txtPelabuhan = new TextField();
	    txtPelabuhan.setName("pelabuhan");  
	    txtPelabuhan.setFieldLabel("Pelabuhan");	    
	    fieldSet.add(txtPelabuhan);
	    
	    txtPic = new TextField();
	    txtPic.setName("pic");  
	    txtPic.setFieldLabel("PIC");	    
	    fieldSet.add(txtPic);
	    
	    txtNoTelp= new TextField();
	    txtNoTelp.setName("telp");  
	    txtNoTelp.setFieldLabel("Telp");	    
	    fieldSet.add(txtNoTelp);
	    
	    txtKeterangan = new TextArea();
	    txtKeterangan.setName("keterangan");  
	    txtKeterangan.setFieldLabel("Keterangan");	    
	    fieldSet.add(txtKeterangan);
	    
	    panel.add(fieldSetFilter);  
	    panel.add(fieldSet);  	

	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    
	    p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) { 
	    	  	Map mapParam = new FastMap();
	    		mapParam.put("no_pengiriman", txtNoPengiriman.getRawValue());	    		
	    		mapParam.put("pelabuhan", txtPelabuhan.getRawValue());
	    		mapParam.put("pic", txtPic.getRawValue());
	    		mapParam.put("keterangan", txtKeterangan.getRawValue());
	    		mapParam.put("telp", txtNoTelp.getRawValue());
	    		mapParam.put("status", "SHIPMENT");
	    		mapParam.put("tanggal", txtTgl.getRawValue());
	    		mapParam.put("volume", txtVolume.getRawValue());
	    		mapParam.put("tgl_ta", txtTglEta.getRawValue() + " " + txtEta.getRawValue());
	    		mapParam.put("tgl_td", txtTglEtd.getRawValue() + " " + txtEtd.getRawValue());
	    		mapParam.put("user", Registry.get("whoAmI").toString());
	    		mapParam.put("app_access", "WEB");
	    		mapParam.put("no_pengajuan", txtNoPreshipment.getRawValue());
	    		if (txtNoPengiriman.getRawValue().equals("")){
	    			mapParam.put("crud", "CREATE");
	    		}else{
	    			mapParam.put("crud", "UPDATE");
	    		}
	    		service.insertPengirimanBB("PENGIRIMAN", mapParam,new AsyncCallback<List<Map>>() {
	    			public void onFailure(Throwable caught) {
	    				GWT.log(caught.getMessage(), null);
	    			}
	
	    			public void onSuccess(List<Map> result) {	
	    				storeResult.removeAll();
	    				storeResult.add(ClientModule.setListBaseModelFromListMap(result));
	    			}
	    		});
	    		
	    		getListPengajuan(cboRakor.getValue().get("no_rakor").toString(), "SHIPMENT", 
		    			  cboPembangkit.getValue().get("id_pltu").toString());
	      }  
	    }));  
	    
	    p.addButton(new Button("Delete", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	    Map mapParam = new FastMap();
		    		mapParam.put("no_pengiriman", txtNoPengiriman.getRawValue());	    		
		    		mapParam.put("pelabuhan", txtPelabuhan.getRawValue());
		    		mapParam.put("pic", txtPic.getRawValue());
		    		mapParam.put("keterangan", txtKeterangan.getRawValue());
		    		mapParam.put("telp", txtNoTelp.getRawValue());
		    		mapParam.put("status", "SHIPMENT");
		    		mapParam.put("tanggal", txtTgl.getRawValue());
		    		mapParam.put("volume", txtVolume.getRawValue());
		    		mapParam.put("tgl_ta", txtTglEta.getRawValue() + " " + txtEta.getRawValue());
		    		mapParam.put("tgl_td", txtTglEtd.getRawValue() + " " + txtEtd.getRawValue());
		    		mapParam.put("user", Registry.get("whoAmI").toString());
		    		mapParam.put("app_access", "WEB");
		    		mapParam.put("no_pengajuan", txtNoPreshipment.getRawValue());
	    			mapParam.put("crud", "DELETE");
		    		service.insertPengirimanBB("PENGIRIMAN", mapParam,new AsyncCallback<List<Map>>() {
		    			public void onFailure(Throwable caught) {
		    				GWT.log(caught.getMessage(), null);
		    			}
		
		    			public void onSuccess(List<Map> result) {	
		    				storeResult.removeAll();
		    				storeResult.add(ClientModule.setListBaseModelFromListMap(result));
		    				getListPengajuan(cboRakor.getValue().get("no_rakor").toString(), "SHIPMENT", 
					    			  cboPembangkit.getValue().get("id_pltu").toString());
		    			}
		    		});	    		
		    		
		    		panel.reset();
		      }  
		    }));  
	    
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  panel.reset();
		      }  
		    }));  

	    panel.add(p);
	    
	    return panel;  
	  }  

	  private Grid createGridPltu(){
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig(); 
		    column = new ColumnConfig("no_pengiriman", "NO PENGIRIMAN", 150);  
		    configs.add(column);  
		    
		    column = new ColumnConfig("no_jadwal", "NO JADWAL", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("tgl_td", "TGL TD", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("tgl_ta", "TGL TA", 150);  
		    configs.add(column); 

		    column = new ColumnConfig("volume", "VOLUME", 100);  
		    configs.add(column);  	  
		    		  
		    column = new ColumnConfig("pelabuhan", "PELABUHAN", 100);  
		    configs.add(column);
		    
		    column = new ColumnConfig("pic", "PIC", 150);  
		    configs.add(column);
		    
		    column = new ColumnConfig("telp", "NO TELP", 150);  
		    configs.add(column);
		    
		    storePerjalanan.setMonitorChanges(true); 
		    ColumnModel cm = new ColumnModel(configs);  
		  
		    gridpltu = new Grid(storePerjalanan, cm);  
		    gridpltu.getView().setEmptyText("Data Empty");  
		    gridpltu.setBorders(true);  
		  
		    return gridpltu;  
	  }   

}
